<template>
  <view :style="[styles]" v-if="loadDone" class="form-area">
    <view v-if="moduleItems">
      <LowCodeComponents
        v-for="items in moduleItems"
        :ref="items.sign + items.id"
        :key="items.id"
        :item="items"
        @event="event"
      />
    </view>
    <view class="default-area" v-else>
      <u--text color="#333" text="请选择表单模块" align="center"></u--text>
    </view>
  </view>
</template>

<script>
import { COMPREIFX } from "../../../libs/const/widget";
export default {
  name: `${COMPREIFX}form-module`,
  props: {
    attribute: Object,
    styles: Object
  },
  components: {
    LowCodeComponents: () => import("../../lc/lc-components.vue")
  },
  data() {
    return {
      moduleItems: null,
      moduleStyle: {},
      loadDone: false
    };
  },
  watch: {
    "attribute.moduleId": {
      handler() {
        this.getModuleInfo();
      },
      deep: true
    }
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      if (this.attribute.moduleId) {
        await this.getModuleInfo();
      }
      this.loadDone = true;
    },
    async getModuleInfo() {
      const api = this.$widget[this.attribute.api.getModuleInfo];
      if (api) {
        await api({ id: this.attribute.moduleId }).then(res => {
          const { items, style } = JSON.parse(res.moduleJson);
          this.moduleItems = items;
          this.moduleStyle = style;
        });
        this.loadDone = true;
      }
    },
    getForm() {
      const result = [];
      for (const key in this.$refs) {
        if (key.indexOf("cus-form") >= 0) {
          result.push(this.$refs[key][0].item);
        }
      }
      return result;
    },
    async trackFormValidate() {
      const stack = [];
      for (const key in this.$refs) {
        if (key.indexOf("cus-form") >= 0) {
          stack.push(
            this.$refs[key][0].$children[0].$children[0].validate().then()
          );
        }
      }
      const res = await Promise.all(stack);
      for (const item of res) {
        if (item !== undefined) {
          return item;
        }
      }
    },
    event(e) {
      this.$emit("event", e);
    }
  }
};
</script>

<style lang="scss" scoped>
.module-area {
  overflow: hidden;
}
.default-area {
  width: 100%;
  height: 175rpx;
  background-color: #d4d3d3;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
